package com.woniu.airent.controller;

import com.woniu.airent.dto.ExtraDto;
import com.woniu.airent.dto.HouseDto;
import com.woniu.airent.dto.ImgsDto;
import com.woniu.airent.dto.ItemsDto;
import com.woniu.airent.service.HouseService;
import com.woniu.airent.utils.TXYunUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.*;

@Controller
@RequestMapping("house")
public class HouseController {
    @Autowired
    HouseService houseService;

    @RequestMapping("/issueHouse")
    @ResponseBody
    public String issueHoue(HouseDto house,
                            @DateTimeFormat(pattern = "yyyy-MM-dd") Date date,
                            @RequestParam(value = "extrasCollection[]") String[] extrasCollection,
                            @RequestParam(value = "itemsCollection[]") String[] itemsCollection,
                            @RequestParam(value = "imgsPath[]") String[] imgPath,
                            HttpServletRequest request) {

//        User user = (User) request.getSession().getAttribute("user");
//        house.setUserId(user.getUserId());
        int userId = 1;
        house.setUserId(userId);
        house.setHouseNumber("houseNum");
        house.setLiveDate(date);
        house.setUpdateDate(new Date());
        house.setRentDate(new Date());
        house.setHouseState(0);
        house.setExamine(0);

        List<ItemsDto> items = new ArrayList<>();
        for (int i = 0; i < itemsCollection.length; i++) {
            ItemsDto itemsDto = new ItemsDto();
            itemsDto.setItemId(Integer.parseInt(itemsCollection[i]));
            items.add(itemsDto);
        }
        house.setItems(items);

        List<ExtraDto> extras = new ArrayList<>();
        for (int i = 0; i < extrasCollection.length; i++) {
            ExtraDto extraDto = new ExtraDto();
            extraDto.setExtraId(Integer.parseInt(extrasCollection[i]));
            extras.add(extraDto);
        }
        house.setExtras(extras);

        List<ImgsDto> imgs = new ArrayList<>();
        for (int i = 0; i < imgPath.length; i++) {
            ImgsDto imgsDto = new ImgsDto();
            imgsDto.setImgAdress(imgPath[i]);
            imgs.add(imgsDto);
        }
        house.setImgs(imgs);

        System.out.println(house);

        int i = houseService.addHouse(house);
        return "success";
    }


    //暂时弃用
    @PostMapping(value = "/addImg")
    @ResponseBody
    public Map<String, String> addImg(HttpServletRequest request, HttpServletResponse response, @RequestParam("imgs") MultipartFile multipartFiles) {
        //生成图片名称（6位uuid+.png）
        String imgName = UUID.randomUUID().toString().replaceAll("-", "").substring(0, 6) + ".png";
        //设置本地仓库
        String path = "D:/imgs/";
        File f = new File(path);

        /*
         *保存信息到数据库应该跟随房屋信息一起插入
         *图片写入仓库给前台返回地址
         * 图片写入云也要返回地址
         *
         * */
        //返回给前端的图片地址
        String imgPath = path + imgName;
        //返回值
        Map<String, String> map = new HashMap<>();

        //图片写入本地仓库
        try {
            multipartFiles.transferTo(new File(f, imgName));
            map.put("success", imgPath);

        } catch (IOException e) {
            e.printStackTrace();
            map.put("error", "上传失败");
        }
        return map;
    }


    //腾讯云
    @Value("${tencent.path}")
    private String IMAGE_PATH;
    /**
     * 上传头像
     */
    @RequestMapping("/upload")
    @ResponseBody
    public Map<String, String> upload(@RequestParam("imgs") MultipartFile multipartFile, Model model) throws Exception {
        //获取文件的名称
        String fileName = multipartFile.getOriginalFilename();

        //获取文件后缀
        String prefix = fileName.substring(fileName.lastIndexOf("."));

        //使用uuid作为文件名，防止生成的临时文件重复
        final File excelFile = File.createTempFile("imagesFile-" + System.currentTimeMillis(), prefix);
        //将Multifile转换成File
        multipartFile.transferTo(excelFile);

        //调用腾讯云工具上传文件
        String imageName = TXYunUtil.uploadfile(excelFile, "avatar");

        //程序结束时，删除临时文件
        deleteFile(excelFile);

        //存入图片名称，用于网页显示
        model.addAttribute("imageName", imageName);

        Map<String, String> map = new HashMap<>();
        map.put("success",imageName);

        //返回成功信息
        return map;
    }

    private void deleteFile(File... files) {
        for (File file : files) {
            if (file.exists()) {
                file.delete();
            }
        }
    }

}
